from win32api import GetFileVersionInfo, LOWORD, HIWORD
from common.exchange.exchange2k8 import StorageGroup
from common.exchange.exchange2k10 import MailboxDatabase2010
from common.exchange.exchange2k3 import ExchangeServer
from common.common import Common
import socket
import os

class ServerError(Exception):    
    pass

class Server(object):

    def __init__(self, server_name = None):
        if server_name is None:
            self.server_name = socket.gethostname()
        else:
            self.server_name = server_name
        self.exchange_version = None
        self.common = Common()

    def _get_exchange_version(self):
        try:
            exchange_path = self.common.get_reg_value('HKLM', 'SOFTWARE\\Microsoft\\Exchange\\Setup\\Services')
        except:
            try:
                exchange_path = self.common.get_reg_value('HKLM', 'SOFTWARE\\Microsoft\\ExchangeServer\\v14\\Setup\\Services')
            except:
                return 0,0,0,0
        store_path = os.path.join(exchange_path, 'bin', 'store.exe')	
        try:
            info = GetFileVersionInfo (store_path, "\\")
            ms = info['FileVersionMS']
            ls = info['FileVersionLS']
            version = HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls)
        except:
            version = 0,0,0,0
        self.common.log.debug('exchange version: {0}'.format(version))
        return version

    def get_store(self, name):        
        self.common.log.debug('opening storage group: {0}'.format(name))
        if self._get_exchange_version()[0] is 6:
            self.exchange_version = 6
            return ExchangeServer('CDOEXM.ExchangeServer', self.server_name).get_storage_group(name)
        elif self._get_exchange_version()[0] is 8:
            self.exchange_version = 8
            return StorageGroup(name, self.server_name)
        elif self._get_exchange_version()[0] is 14:
            self.exchange_version = 14
            return MailboxDatabase2010(name)
        else:
            raise ServerError('unknown exchange version installed')